package cn.kgc.listener.rabbitmq.sms;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author YC
 */
@Configuration
public class SmsRabbitConfig {

    @Value("${mq.deadExchangeName}")
    private String deadExchangeName;
    @Value("${mq.deadRoutingKey}")
    private String deadRoutingKey;
    @Value("${mq.enableHandleDlx}")
    private boolean enableHandleDlx;

    @Bean
    public Queue clientQueue() {
        Map<String, Object> args = new HashMap<>(3);
        if (enableHandleDlx) {
            args.put("x-message-ttl", 60000);
            args.put("x-dead-letter-exchange", deadExchangeName);
            args.put("x-dead-letter-routing-key", deadRoutingKey);
            return new Queue("smsMessageQueue", true, false, false, args);
        }
        return new Queue("smsMessageQueue", true, false, false);
    }

    @Bean
    public DirectExchange clientExchange() {
        return new DirectExchange("smsExchange", true, false);
    }

    @Bean
    public Binding clientBinding() {
        return BindingBuilder.bind(clientQueue()).to(clientExchange()).with("smsRoutingKey");
    }

    /**
     * 让ClientMessageListener监听器监听clientQueue队列中的信息,信息是手动确认
     */
    @Bean
    public SimpleMessageListenerContainer simpleMessageListenerContainer2(
            ConnectionFactory connectionFactory,
            SmsMessageInfoListener smsMessageInfoListener
    ) {
        //设置连接工厂
        SimpleMessageListenerContainer simpleMessageListenerContainer =
                new SimpleMessageListenerContainer(connectionFactory);
        //设置处理消息的业务类型
        simpleMessageListenerContainer.setMessageListener(smsMessageInfoListener);
        //信息手动确认信息
        simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        //添加需要监听的队列
        simpleMessageListenerContainer.setExposeListenerChannel(true);
        simpleMessageListenerContainer.setQueueNames("smsMessageQueue");
        return simpleMessageListenerContainer;
    }


}
